<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\model\Merchant as MerchantModel;
use think\Db;

/**
 * 商家管理
 *
 * @icon fa fa-store
 */
class Merchant extends Backend
{
    protected $model = null;
    protected $searchFields = 'merchant_id,phone';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new MerchantModel();
    }

    /**
     * 查看商家列表
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            // 构建状态筛选下拉选项
            $this->view->assign('statusList', [
                '' => __('全部'),
                '1' => __('正常'),
                '0' => __('禁用')
            ]);
            
            // 构建认证状态筛选下拉选项
            $this->view->assign('verificationStatusList', [
                '' => __('全部'),
                '0' => __('未认证'),
                '1' => __('已认证'),
                '2' => __('认证失败')
            ]);
            
            return $this->view->fetch();
        }
        
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        
        $list = $this->model
            ->with(['audit' => function($query) {
                $query->field('merchant_id,store_name,province,city,district,address');
            }])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        
        // 处理状态显示
        $items = $list->items();
        foreach ($items as &$item) {
            // 状态文本
            $item['status_text'] = $item['status'] == 1 ? '正常' : '禁用';
            
            // 认证状态文本
            switch ($item['verification_status']) {
                case 0:
                    $item['verification_status_text'] = '未认证';
                    break;
                case 1:
                    $item['verification_status_text'] = '已认证';
                    break;
                case 2:
                    $item['verification_status_text'] = '认证失败';
                    break;
                default:
                    $item['verification_status_text'] = '未知状态';
            }
            
            // 从关联的audit表获取店铺名称和地址
            if (isset($item['audit']) && $item['audit']) {
                $item['store_name'] = $item['audit']['store_name'] ?? '';
                
                // 组合完整地址：省份 + 城市 + 区县 + 详细地址
                $addressParts = [
                    $item['audit']['province'] ?? '',
                    $item['audit']['city'] ?? '',
                    $item['audit']['district'] ?? '',
                    $item['audit']['address'] ?? ''
                ];
                // 过滤空值并组合
                $addressParts = array_filter($addressParts);
                $item['address'] = implode('', $addressParts);
            } else {
                $item['store_name'] = '';
                $item['address'] = '';
            }
            
            // 格式化时间
            $item['created_at_text'] = $item['created_at'] ? date('Y-m-d H:i:s', is_numeric($item['created_at']) ? (int)$item['created_at'] : strtotime($item['created_at'])) : '';
            $item['last_login_time_text'] = $item['last_login_time'] ? date('Y-m-d H:i:s', is_numeric($item['last_login_time']) ? (int)$item['last_login_time'] : strtotime($item['last_login_time'])) : '从未登录';
            
            // 禁用原因和禁用时间
            $item['disable_reason_text'] = $item['disable_reason'] ?? '';
            $item['disabled_at_text'] = $item['disabled_at'] ? date('Y-m-d H:i:s', is_numeric($item['disabled_at']) ? (int)$item['disabled_at'] : strtotime($item['disabled_at'])) : '';
        }
        
        $result = ['total' => $list->total(), 'rows' => $items];
        return json($result);
    }

    /**
     * 查看详情
     */
    public function detail($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        // 格式化显示数据
        $row['status_text'] = $row['status'] == 1 ? '正常' : '禁用';
        switch ($row['verification_status']) {
            case 0:
                $row['verification_status_text'] = '未认证';
                break;
            case 1:
                $row['verification_status_text'] = '已认证';
                break;
            case 2:
                $row['verification_status_text'] = '认证失败';
                break;
            default:
                $row['verification_status_text'] = '未知状态';
        }
        
        $row['created_at_text'] = $row['created_at'] ? date('Y-m-d H:i:s', is_numeric($row['created_at']) ? (int)$row['created_at'] : strtotime($row['created_at'])) : '';
        $row['last_login_time_text'] = $row['last_login_time'] ? date('Y-m-d H:i:s', is_numeric($row['last_login_time']) ? (int)$row['last_login_time'] : strtotime($row['last_login_time'])) : '从未登录';
        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 启用/禁用商家
     */
    public function toggle($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        $newStatus = $row['status'] == 1 ? 0 : 1;
        $updateData = ['status' => $newStatus, 'updated_at' => time()];
        
        // 如果是禁用操作，需要保存禁用原因
        if ($newStatus == 0) {
            $reason = $this->request->post('reason');
            if (empty($reason)) {
                $this->error('禁用原因不能为空');
            }
            $updateData['disable_reason'] = $reason;
            $updateData['disabled_at'] = time();
        } else {
            // 启用时清空禁用原因和禁用时间
            $updateData['disable_reason'] = null;
            $updateData['disabled_at'] = null;
        }
        
        $result = $this->model->where('id', $ids)->update($updateData);
        
        if ($result !== false) {
            $statusText = $newStatus == 1 ? '启用' : '禁用';
            $this->success("商家{$statusText}成功");
        } else {
            $this->error("操作失败");
        }
    }

    /**
     * 添加商家
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            
            // 检查手机号是否已存在
            if ($this->model->where('phone', $params['phone'])->count() > 0) {
                $this->error('该手机号已被注册');
            }
            
            // 生成商家ID
            $params['merchant_id'] = $this->model->generateMerchantId();
            
            // 密码加密
            $params['password'] = md5($params['password']);
            
            // 设置默认值
            $params['verification_status'] = 0; // 默认未认证
            $params['created_at'] = time();
            $params['updated_at'] = time();
            
            $result = $this->model->allowField(true)->save($params);
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were inserted'));
            }
        }
        return $this->view->fetch();
    }

    /**
     * 编辑商家
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            
            // 检查手机号是否被其他商家使用
            if ($this->model->where('phone', $params['phone'])->where('id', '<>', $ids)->count() > 0) {
                $this->error('该手机号已被其他商家使用');
            }
            
            $params['updated_at'] = time();
            
            $result = $row->allowField(true)->save($params);
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 重置密码
     */
    public function resetPassword($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        if ($this->request->isPost()) {
            $newPassword = $this->request->post('password');
            if (empty($newPassword)) {
                $this->error('新密码不能为空');
            }
            
            $result = $this->model->where('id', $ids)->update(['password' => md5($newPassword)]);
            
            if ($result !== false) {
                $this->success("密码重置成功");
            } else {
                $this->error("密码重置失败");
            }
        }
        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}